package com.edu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.edu.common.exception.ServiceException;
import com.edu.common.utils.StringUtils;
import com.edu.common.utils.bean.BeanValidators;
import com.edu.common.utils.file.ImageUtils;
import com.edu.system.domain.TTeacher;
import com.edu.system.mapper.TTeacherMapper;
import com.edu.system.service.ISysConfigService;
import com.edu.system.service.ITTeacherService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 教师Service业务层处理
 *
 * @author xxxx
 * @date 2023-12-17
 */
@Slf4j
@Service
public class TTeacherServiceImpl implements ITTeacherService {
    @Autowired
    private TTeacherMapper tTeacherMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Value("${avatar.teacherDefault}")
    private String teacherDefaultAvatar;

    /**
     * 查询教师
     *
     * @param id 教师主键
     * @return 教师
     */
    @Override
    public TTeacher selectTTeacherById(Long id) {
        return tTeacherMapper.selectTTeacherById(id);
    }

    /**
     * 查询教师列表
     *
     * @param tTeacher 教师
     * @return 教师
     */
    @Override
    public List<TTeacher> selectTTeacherList(TTeacher tTeacher) {
        return tTeacherMapper.selectTTeacherList(tTeacher);
    }

    @Override
    public List<TTeacher> selectTeacherList(List<Long> ids) {
        return tTeacherMapper.listByIds(ids);
    }

    @Override
    public Map<Long, String> selectTeacherMap(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return new HashMap<>();
        }
        return this.selectTeacherList(ids)
            .stream().collect(Collectors.toMap(TTeacher::getId, TTeacher::getName));
    }

    @Override
    public TTeacher selectByEmployeeId(String employeeId) {
        TTeacher teacher = new TTeacher();
        teacher.setEmployeeId(employeeId);
        List<TTeacher> tTeachers = this.selectTTeacherList(teacher);
        return Optional.ofNullable(tTeachers)
            .filter(CollectionUtils::isNotEmpty)
            .map(a -> a.get(0))
            .orElseGet(() -> null);
    }

    @Override
    public TTeacher checkAndSaveByCode(String teacherName, String code) {
        TTeacher teacher = new TTeacher();
        teacher.setEmployeeId(code);
        List<TTeacher> tTeachers = tTeacherMapper.selectTTeacherList(teacher);

        return Optional.ofNullable(tTeachers)
            .filter(CollectionUtils::isNotEmpty)
            .map(a -> a.get(0))
            .orElseGet(() -> {
                teacher.setName(teacherName);
                this.insertTTeacher(teacher);
                return teacher;
            });
    }

    /**
     * 新增教师
     *
     * @param tTeacher 教师
     * @return 结果
     */
    @Override
    public int insertTTeacher(TTeacher tTeacher) {
        if (StrUtil.isBlank(tTeacher.getAvatar())){
            tTeacher.setAvatar(ImageUtils.getDefaultImage(teacherDefaultAvatar));
        }
        if (this.checkIsExist(tTeacher.getEmployeeId()) != null){
            throw new ServiceException("教师已存在:" + tTeacher.getEmployeeId());
        }
        return tTeacherMapper.insertTTeacher(tTeacher);
    }

    public TTeacher checkIsExist(String employeeId) {
        TTeacher t = new TTeacher();
//        t.setName(name);
        t.setTelephone(employeeId);
        List<TTeacher> list = tTeacherMapper.realSearchTeacherList(t);
        if (CollectionUtils.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }

    /**
     * 修改教师
     *
     * @param tTeacher 教师
     * @return 结果
     */
    @Override
    public int updateTTeacher(TTeacher tTeacher) {
        TTeacher teacher = this.checkIsExist(tTeacher.getEmployeeId());
        if (teacher != null && !teacher.getId().equals(tTeacher.getId())){
            throw new ServiceException("教师已存在:" + tTeacher.getEmployeeId());
        }

        return tTeacherMapper.updateTTeacher(tTeacher);
    }

    /**
     * 批量删除教师
     *
     * @param ids 需要删除的教师主键
     * @return 结果
     */
    @Override
    public int deleteTTeacherByIds(Long[] ids) {
        return tTeacherMapper.deleteTTeacherByIds(ids);
    }

    /**
     * 删除教师信息
     *
     * @param id 教师主键
     * @return 结果
     */
    @Override
    public int deleteTTeacherById(Long id) {
        return tTeacherMapper.deleteTTeacherById(id);
    }

    @Override
    public long getCnt() {
        return tTeacherMapper.teacherCnt();
    }


    /**
     * 导入教师数据
     *
     * @param tList        教师数据列表
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<TTeacher> tList, String operName) {
        if (StringUtils.isNull(tList) || tList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TTeacher t : tList) {
            try {
                // 验证是否存在这个用户
                TTeacher teacher = checkIsExist(t.getEmployeeId());
                if (StringUtils.isNull(teacher)) {
                    BeanValidators.validateWithException(validator, t);
                    tTeacherMapper.insertTTeacher(t);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、教师 " + t.getName() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、教师 " + t.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、教师 " + t.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
